package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**
 * 东方航空
 * @author 0707
 * @date 2011-3-5
 * @description TODO
 */
public class GetFlightListMU {

	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getResultInfo(QueryInfo queryInfo){
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    //使用POST请求，赋值post数据
			postData.put("cond.tripType", "OW");  //单程
			postData.put("cond.depCode", queryInfo.getOrgCity());  //出发机场
			postData.put("cond.arrCode", queryInfo.getDesCity());  //到达机场
 

			postData.put("cond.depDate", queryInfo.getDateString());  //出发日期
			postData.put("cond.arrDate", "");  //返回日期
			postData.put("cond.depCodeInt", "");  //出发城市
			postData.put("cond.arrCodeInt", "");  //到达城市
			postData.put("cond.depDateInt", "");  //出发日期
			postData.put("cond.depCodeIntRt", ""); //出发城市
			postData.put("cond.arrCodeIntRt", "");  //到达城市
			postData.put("cond.depDateIntRt", "");
			postData.put("cond.cabinRank", "ECONOMY");  //舱位等级
			postData.put("cond.adultNumber", "1");  //成人
			postData.put("cond.childNumber", "0");  //儿童
			postData.put("cond.infantNumber", "0");  //婴儿
			postData.put("cond.sortType", "1");
			postData.put("cond.isInternationalFlight", "331");
			postData.put("cond.region", "CN");
 
			try { 
				responseText = proxy.doRequest(
		 	    "http://www.ce-air.com/mu/front/reservation/flight-search!doFlightSearch.shtml", postData, header,"UTF-8");
				resultInfo = (ResultInfo)analyzeResopnseText(responseText);
				}
		        catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
		        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
		  	return resultInfo;
		}
		
		
		/**
		 * 根据东航网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 */
	    public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象
		      String[] parts = source.split("<tr flightinfourl='/mu/front/reservation/flight-search!showInfo.shtml\\?flight="); //将每一个航班区分开来
 
			     String[] airPort = new String[2];  //出发机场和目的机场
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			     regexSB.append("<img src=\"/mu/images/icon_cea_small_whitebg.gif\" class=\"flightnumber\" />\\s*"); 
			     regexSB.append("</td>\\s*<td>\\s*<input type=\"radio\" checked=\"checked\" name=\"flight_radio\" value=\"(.*?)&\\d{1,3}\" id=\"class_select\" style=\"display: none;\" />");
			     regexSB.append("(.*?)\\s*</td>\\s*<td mark=\"order_time\">(.*?)&rarr;(.*?)</td>\\s*");
			     regexSB.append("<td>\\s*<span class=\"a_flightnumber\">(.*?)</span>\\s*</td>");
			     //航班号  ，航班号+代码共享 ，出发时间，降落时间。
			     String regex =regexSB.toString();
			     String priceRegex = "";

			     priceRegex = "<td cabin='(\\w)\\|(.*?)\\|(.*?)'>\\s*<span style=\"margin-top: 0px\"> <input name=\"segpay_memb_radio\" type=\"radio\" value=\"(.*?)&\\w{1}\"\\s*pricedisplay=\".*?\"\\s*/>\\s*<span>";
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
			     Pattern pPrice = Pattern.compile(priceRegex,Pattern.CASE_INSENSITIVE);
// <td cabin='F|不得签转|不得签转'>                                                <span style="margin-top: 0px"> <input name="segpay_memb_radio" type="radio" value="2580.0&F" pricedisplay="" /><span>￥2,580                                                </span>
// <td cabin='P|不得签转；若更改至3天后的。|不得签转RMYXSUPY'>                      <span style="margin-top: 0px"> <input name="segpay_memb_radio" type="radio" value="1350.0&P" pricedisplay="" />	
			     FlightInfo tempInfo = null;
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
			     
			     //依次取出每个航班的信息,因为parst[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 		     		 
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
			     Matcher matcher = p.matcher(parts[j]);
			     if(matcher.find())   //匹配航班信息
			     {
			    	 String flightNo = matcher.group(1).trim();
			    	 String flightNoAndShareCode = matcher.group(2).trim();
			    	 tempInfo.setFlightNo(flightNo);  //航班号
			    	//判断是否是代码共享
			    	 if(!flightNo.equals(flightNoAndShareCode)){  //如果flightNoAndShareCode不光只有航班号
			    		 String regexTemp = "<img src=\"/mu/images/code_share.gif\" class=\"code_share\" tips=\"代码共享航班，实际承运航班为(.*?)！<br/>.*?\" />";
			    		 Pattern pTemp = Pattern.compile(regexTemp);
			    		 Matcher maTemp  = pTemp.matcher(flightNoAndShareCode);
			    		 if(maTemp.find()){   //如果匹配成功，则为代码共享航班
			    			 tempInfo.setShareCodeFlag(true);
			    			 tempInfo.setShareCode(maTemp.group(1).toString()); 
			    		 }
			    		 
			    		 //匹配是否经停
			    		 if (flightNoAndShareCode.indexOf("class=\"pass_stop\"")>=0) {
							tempInfo.setStopOver(true);
						}
			    	 }
			    	 //判断代码共享结束
			    	 tempInfo.setTakeOffTime(matcher.group(3).trim());
			    	 tempInfo.setArriveTime(matcher.group(4).trim());
			    	 tempInfo.setPlaneType(matcher.group(5).trim());
			     }
			    	 //分析价格start
			    	 Matcher mPrice = pPrice.matcher(parts[j]);
			    	 double tempMinPrice = 0.0;
			    	 double tempMaxPrice = 0.0;
			    	 boolean isFirst = true;
			    	 while(mPrice.find()){
			    		  priceInfo = new PriceInfo();
			    		  String remind1 = mPrice.group(2);
			    		  String remind2 = mPrice.group(3);
                        if(remind1!=null&&remind2!=null&&remind1.trim().length()>0&&remind2.trim().length()>0){ //如果需知不为空
                        	if(remind1.equals(remind2)){   //因为东航需知有两个，用|隔开，有可能相同
                        		priceInfo.setRemind(remind1);
                        	}else{
                        		priceInfo.setRemind(remind1+"；"+remind2);
                        	}
                        	 
                        	if (priceInfo.getRemind().length()>=100) {
                        		priceInfo.setRemind(priceInfo.getRemind().substring(0, 100));
							}
                        }else {
                        	priceInfo.setRemind("无限制");
						}
			    		  priceInfo.setPrice(Double.parseDouble(mPrice.group(4)));  //价格
				    	  priceInfo.setSpace(mPrice.group(1));   //舱位
				    	  priceList.add(priceInfo);
				    	//一个航班不同cabin的最低和最高价格获取
				    	  if (isFirst) {
				    		  tempMinPrice = priceInfo.getPrice();
				    		  tempMaxPrice = priceInfo.getPrice();
				    		  tempInfo.setMinprice(tempMinPrice);
				    		  tempInfo.setMaxprice(tempMaxPrice);
				    		  isFirst = false;
						}
				    	 
				    	  //获取同一个航班的不同舱位中的最高和最低价格
						     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
						    	 tempMinPrice = priceInfo.getPrice();
								}
						     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
						    	 tempMaxPrice = priceInfo.getPrice(); 
							}
						     tempInfo.setMaxprice(tempMaxPrice);
						     tempInfo.setMinprice(tempMinPrice);
			    	 }
			     tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
 		     	 }
				 
 			    resultInfo.setResultList(flightInfos);	  
	 		 	 
				return resultInfo;
		}


}
